package com.suse.jd_system_server.service.impl;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.suse.jd_system_server.auto.mapper.LoginMapper;
import com.suse.jd_system_server.entity.Authority;
import com.suse.jd_system_server.entity.User;
import com.suse.jd_system_server.service.LoginService;
import com.suse.jd_system_server.utils.JwtUtils;
import com.suse.jd_system_server.utils.MD5Utils;
import com.suse.jd_system_server.utils.Result;
import com.suse.jd_system_server.utils.SecurityUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Formatter;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private LoginMapper loginMapper;

    @Autowired
    HttpServletRequest httpServletRequest;

    @Override
    public User selectUserByName(String username) {
        return loginMapper.selectByname(username);
    }

    @Override
    public List<String> selectAuthority(Long userid) {
        return loginMapper.selectAuthority(userid);
    }

    @Override
    public Result Login(String username, String password) {
        //判断密码是否正确
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        if (Objects.isNull(authenticate)) {
            throw new RuntimeException("用户名或密码错误");
        }
        SecurityUser securityUser = (SecurityUser) authenticate.getPrincipal();
        User user = securityUser.getUser();
        System.out.println(user);
        JwtUtils jwtUtils = new JwtUtils();
        String jwt = jwtUtils.createJwt(user.getUserId().intValue(), user.getUserName(), null);
        //存入redis
        try {
            stringRedisTemplate.opsForValue().set("userid:" + user.getUserId(), new ObjectMapper().writeValueAsString(user));
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        httpServletRequest.getSession().setAttribute("userId", user.getUserId());
        httpServletRequest.getSession().setAttribute("userName", user.getUserName());
//        System.out.println("setUserId:"+httpServletRequest.getSession().getAttribute("userId"));
//        System.out.println("setUserId:"+httpServletRequest.getSession().getAttribute("userName"));
        return Result.buildSuccess(jwt).add("userId", user.getUserId());
    }

    @Override
    public Result Register(Map param) {
        LocalDateTime time = LocalDateTime.now();
        String create_time = time.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        param.put("create_time",create_time);
        param.put("update_time",create_time);
        String password = MD5Utils.code(param.get("password").toString());
        param.put("pswd",password);
        loginMapper.register(param);
        return Result.buildSuccess();
    }

    @Override
    public Result Logout(Long userId) {
        Boolean delete = stringRedisTemplate.delete("userid:" + userId);
        if (delete){
            return Result.buildSuccess();
        }else {
            return Result.buildFail("退出登录失败");
        }
    }

    @Override
    public List<Authority> selectRoles(Long role_id) {
        return loginMapper.selectAuthorityList(role_id);
    }

    @Override
    public List<Authority> selectallAuthority() {
        return loginMapper.selectallAuthority();
    }

    @Override
    public void deleteau(Map param) {
        loginMapper.deleteau(param);
    }

    @Override
    public List<String> selectProvince() {
        return loginMapper.selectProvince();
    }

    @Override
    public List<String> selectCity(String cityName) {
        return loginMapper.selectCity(cityName);
    }
}
